//
//  CompanyRegStep2ViewController.m
//  CarTown
//
//  Created by 熊浩 on 15/7/31.
//  Copyright (c) 2015年 熊浩. All rights reserved.
//

#import "CompanyRegStep2ViewController.h"
#import "CheckboxButton.h"
#import "CityPickerView.h"
#import "PickerTableViewController.h"
#import "JianjieViewController.h"
#import "LCActionSheet.h"
#import "IWUploadParam.h"
#import "PostUitls.h"
#import <MBProgressHUD.h>
#import "ResMode.h"
#import "CompanyRegSuSViewController.h"
#import  <AssetsLibrary/AssetsLibrary.h>
#import <QBImagePickerController/QBImagePickerController.h>

#import "SDPhotoBrowser.h"
#import "WebViewController.h"

#define SCALEFlOALT 0.8

@interface CompanyRegStep2ViewController ()<CityPickerDelegate,UITextFieldDelegate,UIScrollViewDelegate,LCActionSheetDelegate,UIImagePickerControllerDelegate,UINavigationControllerDelegate,QBImagePickerControllerDelegate,SDPhotoBrowserDelegate>
{
    NSInteger postion;
    BOOL isshow;
}
@property (weak, nonatomic) IBOutlet UIButton *address;
@property (weak, nonatomic) IBOutlet UITextField *adress_deep;
@property (weak, nonatomic) IBOutlet CheckboxButton *checkbox;
@property (weak, nonatomic) IBOutlet UITextField *truename;
@property (weak, nonatomic) IBOutlet UITextField *phonenumber;
@property (nonatomic,strong) CityPickerView *pickerview;
@property (weak, nonatomic) IBOutlet UIScrollView *scrollview;
@property (weak, nonatomic) IBOutlet UIButton *xingzhi;

@property (weak, nonatomic) IBOutlet UIButton *jianjie;
@property (nonatomic,strong) UITextField *currtTextFiled;
@property (weak, nonatomic) IBOutlet UIView *zhanshiView;
@property (weak, nonatomic) IBOutlet UIButton *mentou;
@property (weak, nonatomic) IBOutlet UIButton *mendianbtn;
@property (weak, nonatomic) IBOutlet UIButton *mendianbtn2;
@property (weak, nonatomic) IBOutlet UIButton *mendianbtn3;
@property (weak, nonatomic) IBOutlet UIButton *mendianbtn4;
@property (weak, nonatomic) IBOutlet UIView *photoview;
@property (nonatomic,strong) NSMutableArray *photoarray;
@property (nonatomic,strong) UIButton *currtBtn;
@property (nonatomic,strong) UIImagePickerController *picker;
@property (nonatomic,strong) NSArray *btnarray;
@property (nonatomic,copy) NSString *province;
@property (nonatomic,copy) NSString *city;
@property (nonatomic,copy) NSString *district;
@property (nonatomic,assign) NSInteger ctid;
@property (nonatomic,strong) UUImageAvatarBrowser *brower;
@end

@implementation CompanyRegStep2ViewController
+(instancetype)viewcontroller{
    CompanyRegStep2ViewController *cr2vc=[XHMianStory instantiateViewControllerWithIdentifier:@"companyregstep2"];
    return cr2vc;
}
- (IBAction)pushtoAgreement:(id)sender {
    WebViewController *webvc=[WebViewController ViewController];
    webvc.type=Agreement;
    [self.navigationController pushViewController:webvc animated:YES];
}

-(NSMutableArray *)photoarray{
    if (_photoarray==nil) {
        _photoarray=[NSMutableArray array];
        
    }
    return _photoarray;
}

- (IBAction)mentou:(UIButton *)sender {
    self.currtBtn=sender;
    if (sender.isSelected) {
        [self showHasActionSheet:sender.tag];
    }else{
        [self showActionSheet:sender.tag];
        
    }
    
}
-(NSArray *)btnarray{
    if (_btnarray==nil) {
        _btnarray=@[self.mentou,self.mendianbtn,self.mendianbtn2,self.mendianbtn3,self.mendianbtn4];
    }
    return _btnarray;
}
-(void)citypicker:(NSString *)procestr city:(NSString *)citystr dist:(NSString *)dist{
    self.province=procestr;
    self.city=citystr;
    self.district=dist;
}



- (void)viewDidLoad {
    [super viewDidLoad];
    self.navigationItem.title=@"公司注册";
   
    
    self.scrollview.delegate=self;
    self.adress_deep.delegate=self;
    self.truename.delegate=self;
    self.phonenumber.delegate=self;
//    [self registerForKeyboardNotifications];
    // Do any additional setup after loading the view.
}

//-(void)dealloc{
//    [[NSNotificationCenter defaultCenter]removeObserver:self];
//}


-(UIStatusBarStyle)preferredStatusBarStyle{
    return UIStatusBarStyleLightContent;
}
- (IBAction)xingzhiclick:(id)sender {
    
    PickerTableViewController *picker=[PickerTableViewController picker];
    picker.currtpostion=postion;
    picker.block=^(NSString *str,NSInteger ctid, NSInteger currtpositon){
        postion=currtpositon;
        self.ctid=ctid;
        [self.xingzhi setTitle:str forState:UIControlStateNormal];
        [self.xingzhi setTitleColor:UIColorWithRGB(44, 44, 44) forState:UIControlStateNormal];
    };
    [self.navigationController pushViewController:picker animated:YES];

}

-(void)qb_imagePickerControllerDidCancel:(QBImagePickerController *)imagePickerController{
    [self dismissViewControllerAnimated:YES completion:nil];
}





-(void)qb_imagePickerController:(QBImagePickerController *)imagePickerController didSelectAssets:(NSArray *)assets{
    NSMutableArray *marray=[NSMutableArray array];
    UIButton *btn=self.btnarray[imagePickerController.view.tag];

    [self dismissViewControllerAnimated:YES completion:^{
        for (ALAsset *asset in assets) {
            
            UIImage *image=[UIImage imageWithCGImage:[[asset defaultRepresentation] fullScreenImage]];
            [marray addObject:image];
            
        }
        if (btn.isSelected) {
            [btn setImage:marray[0] forState:UIControlStateSelected];
        }else{
            if (btn.tag==0) {
                [btn setImage:marray[0] forState:UIControlStateSelected];
                btn.selected=YES;
            }else{
            
            [self.photoarray addObjectsFromArray:marray];
            [self reloadImage];
            }
        
        }
    }];
    
}

-(void)reloadImage{
    for (int i=0; i<4; i++) {
        UIButton *btn=self.btnarray[i+1];
        if (i<self.photoarray.count) {
            [btn setImage:self.photoarray[i] forState:UIControlStateSelected];
             btn.selected=YES;
             btn.hidden=NO;
        }else{
            btn.selected=NO;
            if (i==self.photoarray.count) {
                btn.hidden=NO;
            }else{
                btn.hidden=YES;
            }
        }
    }
}

- (IBAction)jianjie:(id)sender {
    JianjieViewController *jianvc=[[JianjieViewController alloc]init];
    jianvc.block=^(NSString *str){
        if (![str isEqualToString:@""]) {
            [self.jianjie setTitle:str forState:UIControlStateNormal];
            [self.jianjie setTitleColor:UIColorWithRGB(44, 44, 44) forState:UIControlStateNormal];
        }
    };
    [self.navigationController pushViewController:jianvc animated:YES];
}


- (IBAction)postclick:(UIButton *)sender {
    if ([self checkForm]) {
        [self upload];
    }
    
}
//- (void)registerForKeyboardNotifications
//{
//    [[NSNotificationCenter defaultCenter] addObserver:self
//                                             selector:@selector(keyboardWasShown:)
//                                                 name:UIKeyboardDidShowNotification object:nil];
//    
//    [[NSNotificationCenter defaultCenter] addObserver:self
//                                             selector:@selector(keyboardWillBeHidden:)
//                                                 name:UIKeyboardWillHideNotification object:nil];
//    
//}
//
//// Called when the UIKeyboardDidShowNotification is sent.
//- (void)keyboardWasShown:(NSNotification*)aNotification
//{
//    NSDictionary* info = [aNotification userInfo];
//    CGSize kbSize = [[info objectForKey:UIKeyboardFrameBeginUserInfoKey] CGRectValue].size;
//    
//    UIEdgeInsets contentInsets = UIEdgeInsetsMake(0.0, 0.0, kbSize.height, 0.0);
//    self.scrollview.contentInset = contentInsets;
//   self.scrollview.scrollIndicatorInsets = contentInsets;
//    
//    // If active text field is hidden by keyboard, scroll it so it's visible
//    // Your application might not need or want this behavior.
//    CGRect aRect = self.view.frame;
//    aRect.size.height -= kbSize.height;
//    if (!CGRectContainsPoint(aRect, self.currtTextFiled.frame.origin) ) {
//        CGPoint scrollPoint = CGPointMake(0.0, self.currtTextFiled.frame.origin.y-kbSize.height);
//        [self.scrollview setContentOffset:scrollPoint animated:YES];
//    }
//}

//- (void)keyboardWillBeHidden:(NSNotification*)aNotification
//{
//    UIEdgeInsets contentInsets = UIEdgeInsetsZero;
//    self.scrollview.contentInset = contentInsets;
//    self.scrollview.scrollIndicatorInsets = contentInsets;
//}
-(void)scrollViewWillBeginDragging:(UIScrollView *)scrollView{
    [self.view becomeFirstResponder];
}

-(void)textFieldDidBeginEditing:(UITextField *)textField{
    self.currtTextFiled=textField;
}

-(void)keyboardshow:(NSNotification *)notice{
    
    NSDictionary * info = [notice userInfo];
    NSValue *avalue = [info objectForKey:UIKeyboardFrameEndUserInfoKey];
    CGRect keyboardframe=[avalue CGRectValue];
    NSValue *animationDurationValue = [info objectForKey:UIKeyboardAnimationDurationUserInfoKey];
    NSTimeInterval animationDuration;
    [animationDurationValue getValue:&animationDuration];
    [UIView animateWithDuration:animationDuration animations:^{
        if (!isshow) {
            self.view.y=-keyboardframe.size.height;
           
            isshow=YES;
        }else{
            self.view.y=0;
            isshow=NO;
        }

    }];

}

-(BOOL)checkForm{
    if ([self.xingzhi.titleLabel.text isEqualToString:@"请选择商户性质"]) {
        MBProgressHUD *hud=[MBProgressHUD showHUDAddedTo:self.navigationController.view animated:YES];
        hud.labelText=@"请选择商户性质";
        hud.mode = MBProgressHUDModeText;
        hud.margin = 10.f;
        hud.removeFromSuperViewOnHide = YES;
        [hud hide:YES afterDelay:1];
        return false;
    }
    if(!self.mentou.isSelected){
        MBProgressHUD *hud=[MBProgressHUD showHUDAddedTo:self.navigationController.view animated:YES];
        hud.labelText=@"请上传1张门头LOGO照片";
        hud.mode = MBProgressHUDModeText;
        hud.margin = 10.f;
        hud.removeFromSuperViewOnHide = YES;
        [hud hide:YES afterDelay:1];
        return false;
    }
    if (!self.province||!self.city||!self.district) {
        MBProgressHUD *hud=[MBProgressHUD showHUDAddedTo:self.navigationController.view animated:YES];
        hud.labelText=@"请选择所在省市地区";
        hud.mode = MBProgressHUDModeText;
        hud.margin = 10.f;
        hud.removeFromSuperViewOnHide = YES;
        [hud hide:YES afterDelay:1];
        return false;
    }
    if (self.adress_deep.text.length==0) {
        MBProgressHUD *hud=[MBProgressHUD showHUDAddedTo:self.navigationController.view animated:YES];
        hud.labelText=@"详细地址不能为空";
        hud.mode = MBProgressHUDModeText;
        hud.margin = 10.f;
        hud.removeFromSuperViewOnHide = YES;
        [hud hide:YES afterDelay:1];
        return false;
    }
    if (self.truename.text.length==0) {
        MBProgressHUD *hud=[MBProgressHUD showHUDAddedTo:self.navigationController.view animated:YES];
        hud.labelText=@"联系人姓名不能为空";
        hud.mode = MBProgressHUDModeText;
        hud.margin = 10.f;
        hud.removeFromSuperViewOnHide = YES;
        [hud hide:YES afterDelay:1];
        return false;
    }
    if (self.phonenumber.text.length!=11) {
        MBProgressHUD *hud=[MBProgressHUD showHUDAddedTo:self.navigationController.view animated:YES];
        hud.labelText=@"联系人电话不能为空";
        hud.mode = MBProgressHUDModeText;
        hud.margin = 10.f;
        hud.removeFromSuperViewOnHide = YES;
        [hud hide:YES afterDelay:1];
        return false;
    }
    if (self.checkbox.isChecked==NO) {
        MBProgressHUD *hud=[MBProgressHUD showHUDAddedTo:self.navigationController.view animated:YES];
        hud.labelText=@"请同意用户协议";
        hud.mode = MBProgressHUDModeText;
        hud.margin = 10.f;
        hud.removeFromSuperViewOnHide = YES;
        [hud hide:YES afterDelay:1];
        return false;
    }
    return true;
}

#pragma actionshseet代理方法
-(void)actionSheet:(LCActionSheet *)actionSheet didClickedButtonAtIndex:(NSInteger)buttonIndex{
     if (buttonIndex==actionSheet.btnCount-1) return;
    if (actionSheet.isTag) {
        switch (buttonIndex) {
            case 0:
                [self showimage:actionSheet.tag];
                
                break;
            case 1:
                [self showActionSheet:actionSheet.tag];
                break;
            case 2:
            {
                
                if (actionSheet.tag==0) {
                    self.mentou.selected=NO;
                    [self.mentou setImage:nil forState:UIControlStateSelected];
                }else{
                    [self.photoarray removeObjectAtIndex:actionSheet.tag-1];
                    [self reloadImage];
                }
                
            }
                break;
            default:
                break;
        }
        
        
    }else{
        UIButton *btn=self.btnarray[actionSheet.tag];
        [self switchImagePickerOrActionsheet:btn.isSelected WithTag:actionSheet.tag index:buttonIndex];
    }
    
}
-(void)showimage:(NSInteger)tag{
    
    [self showImageWith:tag-1];
    
}

-(UIImage *)photoBrowser:(SDPhotoBrowser *)browser placeholderImageForIndex:(NSInteger)index{
    if (browser.tag==0) {
        return self.mentou.imageView.image;
    }else{
    return self.photoarray[index];
    }
}

-(void)showImageWith:(NSInteger)index{
    SDPhotoBrowser *browser=[[SDPhotoBrowser alloc]init];
    browser.sourceImagesContainerView =index<0?self.mentou:self.photoview; // 原图的父控件
    browser.imageCount =index<0?1:self.photoarray.count; // 图片总数
    browser.currentImageIndex = index<0?0:index;
    browser.delegate = self;
    browser.tag=index+1;
    [browser show];
}

-(void)switchImagePickerOrActionsheet:(BOOL)ishasimg WithTag:(NSInteger)tag index:(NSInteger)buttonindex{
  
        if (buttonindex==0) {
            [self showCarmera:tag];
        }else{
            UIButton *btn=self.btnarray[tag];
            
            QBImagePickerController *imagePickerController = [QBImagePickerController new];
            imagePickerController.view.tag=tag;
            imagePickerController.delegate = self;
            imagePickerController.allowsMultipleSelection = YES;
            if (btn.isSelected||tag==0) {
                imagePickerController.maximumNumberOfSelection = 1;
            }else{
                
                 imagePickerController.maximumNumberOfSelection = 4-self.photoarray.count;
            }
            imagePickerController.showsNumberOfSelectedAssets = YES;
            
            
            [self presentViewController:imagePickerController animated:YES completion:NULL];
        }
    
}



-(void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info{
    [self dismissViewControllerAnimated:YES completion:^{
        UIImage *image = [info objectForKey:UIImagePickerControllerOriginalImage];
        if (picker.view.tag==0) {
            [self.mentou setImage:image forState:UIControlStateSelected];
            self.mentou.selected=YES;
        }else{
            UIButton *btn=self.btnarray[picker.view.tag];
            if (btn.isSelected) {
                [self.photoarray replaceObjectAtIndex:picker.view.tag-1 withObject:image];
            }else{
                [self.photoarray addObject:image];
            }
            [self reloadImage];
        }
    }];
}

-(void)imagePickerControllerDidCancel:(UIImagePickerController *)picker{
    [self dismissViewControllerAnimated:YES completion:nil];
}
- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}
-(void)upload{
    
    MBProgressHUD *hud=[MBProgressHUD showHUDAddedTo:self.navigationController.view animated:YES];
    hud.labelText=@"正在上传...";
    hud.mode = MBProgressHUDModeIndeterminate;
    hud.margin = 10.f;
    hud.removeFromSuperViewOnHide = YES;
    NSMutableArray *photoarray=[NSMutableArray array];
    IWUploadParam *yingyeparam=[[IWUploadParam alloc]init];
    yingyeparam.data=[self.yingyeimg compressData:self.yingyeimg toMaxFileSize:DefailutPicSize];
    
   
    yingyeparam.mineType=@"jpeg";
    yingyeparam.paramName=@"c_zhipic";
    yingyeparam.fileName=@"c_zhipic.jpeg";
    [photoarray addObject:yingyeparam];
    IWUploadParam *namez=[[IWUploadParam alloc]init];
    namez.data=[self.followimg compressData:self.followimg toMaxFileSize:DefailutPicSize];
    namez.mineType=@"jpeg";
    namez.paramName=@"c_namez";
    namez.fileName=@"c_namez.jpeg";
    [photoarray addObject:namez];
    IWUploadParam *namef=[[IWUploadParam alloc]init];
    namef.data=[self.backimg compressData:self.backimg toMaxFileSize:DefailutPicSize];
    namef.mineType=@"jpeg";
    namef.paramName=@"c_namef";
    namef.fileName=@"c_namef.jpeg";
    [photoarray addObject:namef];
    IWUploadParam *handwith=[[IWUploadParam alloc]init];
    handwith.data=[self.shouchiimg compressData:self.shouchiimg toMaxFileSize:DefailutPicSize];
    handwith.mineType=@"jpeg";
    handwith.paramName=@"c_handwith";
    handwith.fileName=@"c_handwith.jpeg";
    [photoarray addObject:handwith];
    IWUploadParam *ment=[[IWUploadParam alloc]init];
    ment.data=[[self.mentou currentImage] compressData:[self.mentou currentImage] toMaxFileSize:DefailutPicSize];
    ment.mineType=@"jpeg";
    ment.paramName=@"c_ment";
    ment.fileName=@"c_ment.jpeg";
     [photoarray addObject:ment];
    NSMutableArray *imgstrarray=[NSMutableArray array];
    

    if (self.mendianbtn.isSelected) {
        NSData *imagedata=[UIImage compressData:[self.mendianbtn currentImage] toMaxFileSize:DefailutPicSize];
        NSString *base64str=[imagedata imageBase64Data:imagedata];
        [imgstrarray addObject:base64str];
    }
    if (self.mendianbtn2.isSelected) {
        NSData *imagedata=[UIImage compressData:[self.mendianbtn2 currentImage] toMaxFileSize:DefailutPicSize];
        NSString *base64str=[imagedata imageBase64Data:imagedata];
        [imgstrarray addObject:base64str];    }
    if (self.mendianbtn3.isSelected) {
        NSData *imagedata=[UIImage compressData:[self.mendianbtn3 currentImage] toMaxFileSize:DefailutPicSize];
        NSString *base64str=[imagedata imageBase64Data:imagedata];
        [imgstrarray addObject:base64str];
    }
    if (self.mendianbtn4.isSelected) {
        NSData *imagedata=[UIImage compressData:[self.mendianbtn4 currentImage] toMaxFileSize:DefailutPicSize];
        NSString *base64str=[imagedata imageBase64Data:imagedata];
        [imgstrarray addObject:base64str];
    }
    
    
    NSMutableDictionary *params=[NSMutableDictionary dictionary];
    params[@"action"]=Regparams;
    params[@"regtype"]=CompanyTypeParams;
    params[@"c_username"]=self.cusername;
    params[@"c_pass"]=self.cpassword;
    params[@"c_name"]=self.cname;
    params[@"c_zhizhaonum"]=self.ccode;
    params[@"c_province"]=self.province;
     params[@"c_city"]=self.city;
    params[@"c_district"]=self.district;
    params[@"c_detail"]=self.adress_deep.text;
    params[@"c_ctname"]=self.truename.text;
    params[@"c_ctphone"]=self.phonenumber.text;
    if (imgstrarray.count>0) {
        params[@"shop_imgs"]=[NSString DataTOjsonString:imgstrarray];
    }
    params[@"c_msn"]=[NSString stringWithFormat:@"%ld",self.ctid];
    
    if (![self.jianjie.titleLabel.text isEqualToString:@"请输入100字以内简介"]) {
         params[@"c_intro"]=self.jianjie.titleLabel.text;
    }
   [PostUitls upload:hosturl parameters:params uploadarray:photoarray success:^(id responseobj) {
       NSDictionary *dict=responseobj;
       ResMode *mode=[ResMode modeWithDict:dict];
       NSLog(@"%@",mode.msg);
       if ([mode.state integerValue]==400) {
           [self pushToSuS:mode];
       }
       [hud hide:YES afterDelay:0.5];
       
   } failure:^(NSError *error) {
       NSLog(@"%@",error);
       [hud hide:YES afterDelay:0.5];
   }];
    
}

- (IBAction)checkboxclick:(CheckboxButton *)sender {
    self.checkbox.isChecked=!self.checkbox.isChecked;
    if ( self.checkbox.isChecked) {
        [sender setImage:[UIImage imageNamed:@"circle1"] forState:UIControlStateNormal];
    }else{
        [sender setImage:[UIImage imageNamed:@"circle2"] forState:UIControlStateNormal];
    }

    
}

-(void)pushToSuS:(ResMode *)mode{
    CompanyRegSuSViewController *crsus=[CompanyRegSuSViewController viewcontroller];
    crsus.mode=mode;
    [self.navigationController pushViewController:crsus animated:YES];
}

-(void)showHasActionSheet:(NSInteger)tag{
    
    LCActionSheet *sheet=[[LCActionSheet alloc]initWithTitle:nil buttonTitles:@[@"查看大图",@"重新上传",@"删除"] redButtonIndex:2 delegate:self];
    sheet.tag=tag;
    sheet.isTag=YES;
    [sheet show];
}
-(UIImagePickerController *)picker{
    if (_picker==nil) {
        _picker=[[UIImagePickerController alloc]init];
        _picker.view.backgroundColor = [UIColor whiteColor];
        
        _picker.delegate =self;
       
    }
    return _picker;
}

-(void)showCarmera:(NSInteger)tag{
    UIImagePickerControllerSourceType sourcheType = UIImagePickerControllerSourceTypeCamera;
    self.picker.view.tag=tag;
    self.picker.sourceType=sourcheType;
    [self presentViewController:self.picker animated:YES completion:nil];
}

-(void)showActionSheet:(NSInteger)tag{
    
    LCActionSheet *sheet=[[LCActionSheet alloc]initWithTitle:nil buttonTitles:@[@"拍照",@"从相册中选取"] redButtonIndex:-1 delegate:self];
    sheet.tag=tag;
    [sheet show];
}


-(CityPickerView *)pickerview{
    if (_pickerview==nil) {
        _pickerview=[[CityPickerView alloc]initWithDelegate:self WithColoum:3];
    }
    return _pickerview;
}

- (IBAction)addressclcik:(id)sender {
    [self.scrollview becomeFirstResponder];
    [self.pickerview showinView:self.view];
    
}
-(void)citypicker:(NSString *)city{
    [self.address setTitle:city forState:UIControlStateNormal];
    [self.address setTitleColor:UIColorWithRGB(44, 44, 44) forState:UIControlStateNormal];
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
